package cn.xiaopengstack.trigger.job;

import cn.xiaopengstack.domain.strategy.model.valobj.AwardStockQueueVO;
import cn.xiaopengstack.domain.strategy.model.valobj.UpdateAwardStockVO;
import cn.xiaopengstack.domain.strategy.repository.IStrategyRepository;
import cn.xiaopengstack.domain.strategy.service.raffle.IRaffleStock;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Set;

/**
 * @author jiangyangang
 */
@Component
@Slf4j
public class UpdateAwardStockJob {

    @Resource
    private IRaffleStock raffleStock;

    @Resource
    private IStrategyRepository strategyRepository;


    /**
     * 定时更新库存任务
     * 更新频率：5/s
     */
    @XxlJob("UpdateAwardStockJob")
    public void exec(){
        AwardStockQueueVO queueValue = new AwardStockQueueVO();
        try {
            // 获取已经缓存的生效的奖品副本
            Set<AwardStockQueueVO> cacheAwardRegisterTable = strategyRepository.getCacheAwardRegisterTable();
            for (AwardStockQueueVO queueVO : cacheAwardRegisterTable) {
                queueValue = queueVO;
                AwardStockQueueVO stockVO = raffleStock.takeStockQueueValue(queueVO);

                if (Objects.isNull(stockVO)) {
                    continue;
                }

                log.info("奖品定时任务，策略ID:{}， 奖品ID:{}", queueVO.getStrategyId(), queueVO.getAwardId());

                UpdateAwardStockVO updateVO = UpdateAwardStockVO.builder()
                        .strategyId(stockVO.getStrategyId())
                        .awardId(stockVO.getAwardId())
                        .decrStock(stockVO.getDecrStock()).build();
                raffleStock.updateStrategyAwardStock(updateVO);
            }
        } catch (InterruptedException e) {
            log.error("奖品定时任务-异常 策略ID:{}, 奖品ID:{}", queueValue.getStrategyId(), queueValue.getAwardId(), e);
        }
    }
}
